package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOCK_SHOP_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private CacheClient cacheClient;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryById(Long id) {
        //逻辑过期解决缓存击穿
//        Shop shop = cacheClient.queryWithLogicExpire(
//                RedisConstants.CACHE_SHOP_KEY,
//                id,
//                Shop.class,
//                this::getById,
//                20L, TimeUnit.SECONDS
//        );
        //分布式锁解决缓存击穿
//        Shop shop = cacheClient.queryWithMutex(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);
        //缓存空值解决缓存穿透
        Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);
        if (shop == null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

//    private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);
//    public Shop queryWithLogicExpire(Long id) {
//        String key = RedisConstants.CACHE_SHOP_KEY + id;
//        String shopJson = stringRedisTemplate.opsForValue().get(key);
//        if (StrUtil.isBlank(shopJson)) {
//            return null;
//        }
//        //获取数据
//        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
//        Object data = redisData.getData();
//        Shop shop = BeanUtil.toBean(data, Shop.class);
//        //判断是否过期
//        if (redisData.getExpireTime().isAfter(LocalDateTime.now())){
//            //未过期，返回数据
//            return shop;
//        }
//        //已过期，尝试获取锁
//        if (tryLock(LOCK_SHOP_KEY + id)){
//                CACHE_REBUILD_EXECUTOR.submit(() -> {
//                    try {
//                    saveShop2Redis(id, 30L);
//                    } catch (Exception e) {
//                        throw new RuntimeException(e);
//                    } finally {
//                        unLock(LOCK_SHOP_KEY + id);
//                    }
//                });
//        }
//        return shop;
//    }

//    /**
//     * 缓存击穿
//     * @param id
//     * @return
//     */
//    public Shop queryWithMutex(Long id) {
//        String key = RedisConstants.CACHE_SHOP_KEY + id;
//        String shopJson = stringRedisTemplate.opsForValue().get(key);
//        if (StrUtil.isNotBlank(shopJson)) {
//            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
//            return shop;
//        }
//        if (shopJson != null){
//            return null;
//        }
//        String lockKey = LOCK_SHOP_KEY + id;
//        Shop shop =null;
//        //获取锁
//        try {
//            if (!tryLock(lockKey)){
//                Thread.sleep(50);
//                return queryWithMutex(id);
//            }
//            shop = getById(id);
//            Thread.sleep(200);
//            //存入redis
//            if (shop != null) {
//                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.SECONDS);
//                return shop;
//            }
//            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
//            return null;
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        } finally {
//            unLock(lockKey);
//        }
//    }

    /**
     * 缓存穿透
     * @param
     * @return
     */
//    public Shop queryWithPassThrough(Long id) {
//        String key = RedisConstants.CACHE_SHOP_KEY + id;
//        String shopJson = stringRedisTemplate.opsForValue().get(key);
//        if (StrUtil.isNotBlank(shopJson)) {
//            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
//            return shop;
//        }
//        if (shopJson != null){
//            return null;
//        }
//        Shop shop = getById(id);
//        //存入redis
//        if (shop != null) {
//            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.SECONDS);
//            return shop;
//        }
//        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
//        return null;
//    }

//    private boolean tryLock(String key){
//        boolean isLock = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
//        return BooleanUtil.isTrue(isLock);
//    }
//    private void unLock(String key){
//        stringRedisTemplate.delete(key);
//    }

//    public void saveShop2Redis(Long id,Long expireSeconds) throws InterruptedException {
//        Shop shop = getById(id);
//        Thread.sleep(200);
//        RedisData redisData = new RedisData();
//        redisData.setData(shop);
//        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
//    }
    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        //校验店铺id
        if (shop.getId() == null) {
            return Result.fail("店铺id不能为空");
        }

        boolean result = updateById(shop);
        if (result) {
            stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
            return Result.ok();
        }
        return Result.fail("更新店铺信息失败");
    }
}
